package com.rgs.pay.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.rgs.pay.config.AliPayConfig;
import com.rgs.pay.entity.SysPayKey;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: com-rgs-parent
 * @description: 支付宝下单支付
 * @author: Mr.Ren
 * @create: 2022-12-02 09:59
 **/
public class AliPayService {


    /**
     * 支付宝JSAPI下单支付
     *
     * @param model
     * @param sysPayKey
     * @param pa
     * @return
     * @throws AlipayApiException
     */
    public Map<String, String> aliJSAPIPay(AlipayTradeWapPayModel model, SysPayKey sysPayKey, Map<String, String> pa) throws AlipayApiException {
        Map<String, String> result = new HashMap<>();
        String title = pa.get("title");

        System.out.println("=========================" + title + "==支付宝JSAPI下单开始=========================");
        AliPayConfig aliPayConfig = new AliPayConfig();
        aliPayConfig.ALIPAY_APPID = sysPayKey.getAliNativeAppId();
        aliPayConfig.aliNotifyUrl = sysPayKey.getAliNotifyUrl();
        aliPayConfig.aliReturn_url = sysPayKey.getAliReturnUrl();
        aliPayConfig.ALIPAY_PUBLIC_KEY = sysPayKey.getAliAlipayPublicKey();
        aliPayConfig.APP_PRIVATE_KEY = sysPayKey.getAliPrivateKey();
        AlipayClient alipayClient = aliPayConfig.getAlipayClient();
        //创建API对应的request类(主要是这里变化了)
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(aliPayConfig.aliNotifyUrl);// 异步通知地址
        request.setReturnUrl(aliPayConfig.aliReturn_url);// 同步通知地址
        request.setBizModel(model);
        String form = alipayClient.pageExecute(request).getBody(); //调用SDK生成表单
        if (form != null && form.length() > 0) {
            result.put("code", "SUCCESS");
            result.put("msg", "支付宝下单成功");
            result.put("data", form);
            System.out.println("=========================" + title + "==支付宝JSAPI预下单完成=========================");
        } else {
            result.put("code", "ERROR");
            result.put("msg", "支付宝下单失败");
            System.out.println("=========================" + title + "==支付宝JSAPI预下单失败=========================");
        }
        return result;
    }

}
